package com.heima.leetcode.practice;

/**
 * @description: leetcode 152. 乘积最大子数组
 * @author 勾新杰
 * @version 1.0
 * @date 2025/1/22 10:21
 */
public class E152 {

    /**
     * <h3>方法一：记录最大、最小</h3>
     * @param nums nums数组
     * @return 最大乘积
     */
    public int maxProduct1(int[] nums) {
        int maxSoFar = nums[0];
        int minSoFar = nums[0];
        int max = nums[0];
        for (int i = 1; i < nums.length; i++) {
            if(nums[i] < 0){
                int temp = maxSoFar;
                maxSoFar = minSoFar;
                minSoFar = temp;
            }
            maxSoFar = Math.max(nums[i], maxSoFar * nums[i]);
            minSoFar = Math.min(nums[i], minSoFar * nums[i]);
            max = Math.max(max, maxSoFar);
        }
        return max;
    }

        /**
         * <h3>方法二：从左往右遍历一次，从右往左来一次</h3>
         * @param nums nums数组
         * @return 最大乘积
         */
        public int maxProduct2(int[] nums) {
            int max = nums[0];
            int mul = 1;
            // 1. 从左往右遍历一次
            for (int num : nums) {
                mul *= num;
                if (mul > max) max = mul;
                if (mul == 0) mul = 1;
            }
            mul = 1;
            // 2. 从右往左遍历一次
            for (int i = nums.length - 1; i >= 0; i--) {
                mul *= nums[i];
                if (mul > max) max = mul;
                if (mul == 0) mul = 1;
            }
            return max;
        }
}
